﻿using System;
using System.Collections.Generic;
using CharacterCreation.Business.ViewModels;
using CharacterCreation.Data.Models;

namespace CharacterCreation.Business.Repositories {
    public class RepositoryFactory {
        public static IRepository<ViewModel> Create<ViewModel>(string tag = null) where ViewModel : new() {
           
            if (typeof(ViewModel) == typeof(VMCharacter))
            {
                return (IRepository<ViewModel>)Activator.CreateInstance(typeof(CharacterRepository));
            }


            Type modelType = ModelBinder.Instance.GetModelType(typeof(ViewModel));

            return (IRepository<ViewModel>)Activator
                    .CreateInstance(typeof(Repository<,>)
                    .MakeGenericType(new Type[] { typeof(ViewModel), modelType }));
        }
    }

    public class ModelBinder
    {
        private static ModelBinder modelBinder;
        public static ModelBinder Instance
        {
            get
            {
                if (modelBinder == null)
                {
                    modelBinder = new ModelBinder();
                }
                return modelBinder;
            }
        }


        private Dictionary<Type, Type> modelBindings;

        public void Bind<ViewModel, Model>()
        {
            modelBindings.Add(typeof(ViewModel), typeof(Model));
        }

        public void Bind(Type viewModel, Type model)
        {
            modelBindings.Add(viewModel, model);
        }

        public Type GetModelType(Type viewModelType)
        {
            return modelBindings[viewModelType];
        }

        private ModelBinder()
        {
            modelBindings = new Dictionary<Type, Type>();
            initBindings();
        }

        private void initBindings()
        {
            Bind<VMCharacter, Character>();
            Bind<VMCharacterSkill, CharacterSkill>();
            Bind<VMCharacterStatistic, CharacterStatistic>();
            Bind<VMCharacterStatisticXPDetail, XPDetail>();
            Bind<VMSkill, Skill>();
            Bind<VMRace, Race>();
            Bind<VMSpecial, Special>();


            Bind<VMStrength, Strength>();
            Bind<VMDexterity, Dexterity>();
            Bind<VMFighting, Fighting>();
            Bind<VMConstitution, Constitution>();
            Bind<VMPerception, Perception>();
            Bind<VMIntelligence, Intelligence>();
            Bind<VMWillPower, WillPower>();
            Bind<VMCharisma, Charisma>();
        }
    }
}
